TimHopDongPanel = Ext.extend(AbstractPanel, {
	layout : {
        type : 'vbox',
        align : 'stretch'
    },
    
    height : 900,
    justUseDefaultHotKeys : false,
    initComponent : function() {
    	this.formLabel = new Ext.form.Label({
			cls : 'main-title',
			text : lang.text.menu.timHd.toUpperCase()
		});
		
		this.formLabelContainer = new Ext.Container({
			cls : 'field-align-center',
			items : [this.formLabel]
		});
		
		this.criteriaFieldSet = this.initCriteriaFieldSet();
		var buttonBar1 = this.initSearchButtonBar();
		this.resultTable = this.initResultTable();
		var buttonBar2 = this.initUpdateButtonBar();
    	this.items = [this.formLabelContainer, {xtype : 'spacer', height : 10},
		              this.criteriaFieldSet, {xtype : 'spacer', height : 20},
		              buttonBar1, {xtype : 'spacer', height : 20},
					  this.resultTable, {xtype : 'spacer', height : 20}, buttonBar2];
    	TimHopDongPanel.superclass.initComponent.call(this);
    },
    
    initCriteriaFieldSet : function() {
    	this.maHdTextField = new Ext.form.TextField({
			name : "maHd",
			fieldLabel : lang.text.hd.maHd,
			width : 180,
			selectOnFocus : true,
			style : {
				textTransform : 'uppercase'
			},
			autoCreate: {
	            tag: 'input', type: 'text', size: '20',
	            autocomplete: 'off', maxlength: '10'}
		});
		
		this.doiTruongCombo = new Ext.form.ComboBox({
			addEmptyItemAtFirst : true,
			name : 'nvDoiTruong',
			hiddenName : 'nvDoiTruong-id',
            fieldLabel : lang.text.hd.doiTruong,
            width : 250,
            selectOnFocus : true,
            forceSelection : true,
            mode : 'local',
            triggerAction : 'all',
            valueField : 'id',
            displayField : 'maNv',
            store : new Ext.data.JsonStore({
                fields : ['id', 'maNv']
            })
		});
		
		this.nvBanCombo = new Ext.form.ComboBox({
			addEmptyItemAtFirst : true,
			name : 'nvBan',
			hiddenName : 'nvBan-id',
            fieldLabel : lang.text.hd.nvBan,
            width : 250,
            selectOnFocus : true,
            editable : true,
            forceSelection : true,
            mode : 'local',
            triggerAction : 'all',
            lastQuery : '',
            valueField : 'id',
            displayField : 'maNv',
            store : new Ext.data.JsonStore({
                fields : ['id', 'maNv', 'doiTruong-id']
            })
		});
		
		this.thuNganCombo = new Ext.form.ComboBox({
			addEmptyItemAtFirst : true,
			name : 'nvThuNgan',
			hiddenName : 'nvThuNgan-id',
            fieldLabel : lang.text.hd.thuNgan,
            width : 250,
            selectOnFocus : true,
            editable : true,
            forceSelection : true,
            mode : 'local',
            triggerAction : 'all',
            valueField : 'id',
            displayField : 'maNv',
            store : new Ext.data.JsonStore({
                fields : ['id', 'maNv']
            })
		});
		
		this.daGiaoPhieuChkbox = new Ext.form.Checkbox({
	        autoDestroy : true,
	        name : 'daGiaoPhieu',
	        fieldLabel : lang.text.hd.daGiaoPhieu
	    });
		
		this.ngayBanFromDateField = new ThienTanDateField({
			fieldLabel : lang.text.hd.ngayBanFrom,
			width : 90,
			name: 'ngayBanFrom'
		});
		
		this.ngayBanToDateField = new ThienTanDateField({
			fieldLabel : lang.text.hd.ngayBanTo,
			width : 90,
			name: 'ngayBanTo'
		});
		
		var dateCtn = new Ext.Container({
			layout : 'column',
			defaults : {
				columnWidth : .5
			},
			width : 447,
			items : [Utility.createLayoutForComponent(this.ngayBanFromDateField, 80), 
			         Utility.createLayoutForComponent(this.ngayBanToDateField, 15)]
		});
		
		var leftCtn = new Ext.Container({
			labelWidth : 80,
			layout : 'customizedlayout',
			width : 500,
			items : [this.maHdTextField, this.doiTruongCombo, this.nvBanCombo, dateCtn, this.thuNganCombo, this.daGiaoPhieuChkbox]
		});
		
		this.trangThaiCombo = new Ext.form.ComboBox({
			addEmptyItemAtFirst : true,
			name : 'trangThai',
			hiddenName : 'trangThai',
            fieldLabel : lang.text.hd.hdStatus,
            width : 250,
            selectOnFocus : true,
            editable : true,
            forceSelection : true,
            mode : 'local',
            triggerAction : 'all',
            valueField : 'value',
            displayField : 'text',
            store : new Ext.data.JsonStore({
                fields : ['value', 'text']
            })
		});
		this.tenKhTextField = new Ext.form.TextField({
			name : "kh-hoTen",
			width : 250,
			selectOnFocus : true,
			fieldLabel : lang.text.kh.hoTen,
			autoCreate: {
	            tag: 'input', type: 'text', size: '20',
	            autocomplete: 'off', maxlength: '50'}
		});
		
		this.tinhThanhCombo = new Ext.form.ComboBox({
			addEmptyItemAtFirst : true,
			name : 'tinhThanh',
            fieldLabel : lang.text.kh.tinhThanh,
            width : 250,
            selectOnFocus : true,
            editable : true,
            forceSelection : true,
            mode : 'local',
            triggerAction : 'all',
            valueField : 'maDuLieu',
            displayField : 'giaTri',
            store : new Ext.data.JsonStore({
                fields : ['maDuLieu', 'giaTri']
            })
		});
		
		this.quanHuyenCombo = new Ext.form.ComboBox({
			addEmptyItemAtFirst : true,
			name : 'quanHuyen',
            fieldLabel : lang.text.kh.quanHuyen,
            width : 250,
            selectOnFocus : true,
            editable : true,
            forceSelection : true,
            mode : 'local',
            triggerAction : 'all',
            valueField : 'maDuLieu',
            displayField : 'giaTri',
            store : new Ext.data.JsonStore({
            	url : 'hopDong/reloadQuanHuyenByThanhPho',
            	autoLoad : false,
                fields : ['maDuLieu', 'giaTri']
            })
		});
		
		this.phuongXaCombo = new Ext.form.ComboBox({
			addEmptyItemAtFirst : true,
			name : 'phuongXa',
            fieldLabel : lang.text.kh.phuongXa,
            width : 250,
            selectOnFocus : true,
            editable : true,
            forceSelection : true,
            mode : 'local',
            triggerAction : 'all',
            valueField : 'maDuLieu',
            displayField : 'giaTri',
            store : new Ext.data.JsonStore({
            	url : 'hopDong/reloadPhuongXaByQuanHuyen',
            	autoLoad : false,
                fields : ['maDuLieu', 'giaTri']
            })
		});
		
		var rightCtn = new Ext.Container({
			layout : 'customizedlayout',
			labelWidth : 80,
			width : 500,
			columnWidth: .5,
			items : [this.trangThaiCombo, this.tenKhTextField, 
			         this.tinhThanhCombo, this.quanHuyenCombo, this.phuongXaCombo]
		});
		
		return new Ext.form.FieldSet({
			title : lang.text.kh.khInfo,
			autoHeight : true,
			height : 220,
			layout : 'column',
			items : [leftCtn, {xtype : 'spacer', width : 10}, rightCtn]
		});
    },
    
    initSearchButtonBar : function() {
    	this.timBtn = new Ext.Button({
			width : 40,
			text : lang.text.tim
		});
		
		this.xoaBtn = new Ext.Button({
			width : 100,
			text : lang.text.hd.clearSearch
		});
		
		this.xuatBtn = new Ext.Button({
			width : 100,
			text : lang.text.hd.exportResult
		});
		
		return new Ext.Container({
			layout : 'hbox',
			items : [this.timBtn, {xtype : 'spacer', width : 13}, this.xoaBtn, {xtype : 'spacer', width : 13}, this.xuatBtn]
		});
    },
    
    initResultTable : function() {
    	this.gridStore = new Ext.data.JsonStore({
    		url : 'timHopDong/search',
    		paramNames: {
    			start : 'offset', limit : 'max', sort : 'maHd', dir : 'ASC'
    		},
    		baseParams: {
    			offset : 0, max : tt_default.hd.pagingLimit
    		},
    		root : 'items',
    		totalProperty : 'count',
    		fields : [
    		        {name : 'stt', type : 'int'},
                    {name : 'maHd'},
                    {name : 'maDt'},
                    {name : 'maTn'},
                    {name : 'maNv1'},
                    {name : 'maNv2'},
                    {name : 'khHoTen'},
                    {name : 'trangThaiText'},
                    {name : 'giaTri'},
                    {name : 'tienDaThu'},
                    {name : 'tienConLai'}]
    	});
    	
    	this.gridColModel = new Ext.grid.ColumnModel({
            defaults : {
                sortable : true
            },
            columns : [ {
                id : 'stt',
                header : 'STT',
                dataIndex : 'stt',
                width : 40
            }, {
                id : 'maHd',
                header : lang.text.hd.maHd,
                dataIndex : 'maHd',
                width : 80
            }, {
                id : 'maDt',
                header : lang.text.hd.doiTruong,
                dataIndex : 'maDt',
                width : 50
            }, {
                id : 'maTn',
                header : lang.text.hd.thuNgan,
                dataIndex : 'maTn',
                width : 50
            }, {
                id : 'maNv1',
                header : lang.text.hd.nvBan1,
                dataIndex : 'maNv1',
                width : 80
            }, {
                id : 'maNv2',
                header : lang.text.hd.nvBan2,
                dataIndex : 'maNv2',
                width : 80
            }, {
                id : 'khHoTen',
                header : lang.text.hd.tenKh,
                dataIndex : 'khHoTen',
                width : 200
            }, {
                id : 'trangThaiText',
                header : lang.text.hd.hdStatus,
                dataIndex : 'trangThaiText',
                width : 120
            }, {
                id : 'giaTri',
                header : lang.text.hd.tongTien,
                dataIndex : 'giaTri',
                renderer : function(val) {
                	return Utility.formatThousandSeparator(val);
                },
                width : 90
            }, {
                id : 'tienDaThu',
                header : lang.text.hd.daThu,
                dataIndex : 'tienDaThu',
                renderer : function(val) {
                	return Utility.formatThousandSeparator(val);
                },
                width : 90
            }, {
                id : 'tienConLai',
                header : lang.text.hd.conLai,
                dataIndex : 'tienConLai',
                renderer : function(val) {
                	return Utility.formatThousandSeparator(val);
                },
                width : 110
            }]
        });
    	
    	this.gridBBar = new Ext.PagingToolbar({
    		pageSize : tt_default.hd.pagingLimit,
    		store : this.gridStore,
    		displayInfo : true,
    		displayMsg  : lang.msg.displayResult,
    		emptyMsg : lang.msg.noResultToDisplay,
    		beforePageText : lang.text.beforePageText,
    	    afterPageText : lang.text.afterPageText,
    	    firstText : lang.text.firstText,
    	    prevText : lang.text.prevText,
    	    nextText : lang.text.nextText,
    	    lastText : lang.text.lastText,
    	    refreshText : lang.text.refreshText
        });
    	
    	return new Ext.grid.GridPanel({
    		store : this.gridStore,
    		loadMask: true,
    		height : 260,
    		selModel : new Ext.grid.RowSelectionModel(),
    		colModel : this.gridColModel,
    		bbar : this.gridBBar,
    		viewConfig : {
    			forceFit : true
    		},
    		initEvents : function(){
    	        Ext.grid.GridPanel.superclass.initEvents.call(this);

    	        if(this.loadMask){
    	            this.loadMask = new Ext.LoadMask(this.bwrap,
    	                    Ext.apply({store:this.store, msg: lang.text.searching}, this.loadMask));
    	        }
    	    }
    	});
    },
    
    initUpdateButtonBar : function() {
    	this.doiThuNganCombo = new Ext.form.ComboBox({
			name : 'nvThuNganMoi',
			hiddenName : 'nvThuNganMoi-id',
            fieldLabel : lang.text.hd.doiThuNgan,
            width : 250,
            forceSelection : true,
            mode : 'local',
            triggerAction : 'all',
            valueField : 'id',
            disabled : true,
            displayField : 'maNv',
            store : new Ext.data.JsonStore({
                fields : ['id', 'maNv']
            }), 
            plugins : new CustomizedFieldPlugin()
		});
		this.capNhatThuNganBtn = new Ext.Button({
			width : 110,
			disabled : true,
			text : lang.text.hd.capNhatThuNgan
		});
		
		this.dongHdBtn = new Ext.Button({
			width : 100,
			disabled : true,
			text : lang.text.hd.dongHd
		});
		this.giaoPhieuThuBtn = new Ext.Button({
			width : 100,
			disabled : true,
			text : lang.text.menu.giaoPt
		});
		
		return new Ext.Container({
			layout : 'hbox',
			height : 60,
			items : [Utility.createLayoutForComponent(this.doiThuNganCombo, 115),
			         {xtype : 'spacer', width : 20}, this.capNhatThuNganBtn, 
			         {xtype : 'spacer', width : 20}, this.dongHdBtn,
			         {xtype : 'spacer', width : 20}, this.giaoPhieuThuBtn]
		});
    },
    afterRender : function() {
    	this.submitButtons = [this.timBtn];
    	this.initData();
    	this.doiTruongCombo.on('select', this.reloadNhanVienByDoiTruong, this);
    	this.tinhThanhCombo.on('select', this.reloadQuanHuyenByThanhPho, this);
		this.quanHuyenCombo.on('select', this.reloadPhuongXaByQuanHuyen, this);
    	this.timBtn.on('click', this.search, this);
    	this.xoaBtn.on('click', this.xoaDuLieuTimKiem, this);
    	this.xuatBtn.on('click', this.xuatKetQua, this);
    	this.gridStore.on('load', this.enableUpdateSection, this);
    	this.capNhatThuNganBtn.on('click', this.capNhatThuNgan, this);
    	this.dongHdBtn.on('click', this.dongHd, this);
    	this.giaoPhieuThuBtn.on('click', this.giaoPhieuThu, this);
    	TimHopDongPanel.superclass.afterRender.call(this);
    },
    
    enableUpdateSection : function() {
    	if (this.gridStore.data.items.length > 0) {
			this.doiThuNganCombo.enable();
			this.capNhatThuNganBtn.enable();
			this.dongHdBtn.enable();
			this.giaoPhieuThuBtn.enable();
		} else {
			this.doiThuNganCombo.disable();
			this.capNhatThuNganBtn.disable();
			this.dongHdBtn.disable();
			this.giaoPhieuThuBtn.disable();
		}
    },
    
    initData : function() {
    	Ext.Ajax.request({
            url : 'hopDong/initData',
            params : {
            	"isSearchScreen" : true
            },
            method : 'GET',
            scope : this,
            success : function(response, opts){
                var result = Ext.decode(response.responseText); 
                this.doiTruongCombo.store.loadData(result.doiTruong);
                DisplayType = Ext.data.Record.create([
                                                      {name: "id", type: "number"},
                                                      {name: "maNv", type: "string"}
                                                  ]);
                this.doiTruongCombo.store.insert(1, new DisplayType({
                	id : "NO_DT",
                	maNv : lang.text.noDt
                }));
                this.nvBanCombo.store.loadData(result.nvBan);
                this.thuNganCombo.store.loadData(result.thuNgan);
                this.thuNganCombo.store.insert(1, new DisplayType({
                	id : 'CTY',
                	maNv : lang.text.cty
                }));
                this.tinhThanhCombo.store.loadData(result.tinhThanh);
                this.trangThaiCombo.store.loadData(result.trangThais);
                this.doiThuNganCombo.store.loadData(result.thuNgan);
                this.doiThuNganCombo.store.insert(0, new DisplayType({
                	id : 'CTY',
                	maNv : lang.text.cty
                }));
                this.maHdTextField.focus(true);
            }, 
            failure : function() {
            }
    	});
    },
    
    initHotKey : function() {
    	var defaultHotKeys = this.defaultHotKeys();
    	this.keys = new Ext.KeyMap(this.el, [defaultHotKeys[0], defaultHotKeys[1], {
	        key: 'c',
	        ctrl : true,
	        alt : true,
	        fn: this.xoaDuLieuTimKiem,
	        scope: this
	    }, {
	        key: 'x',
	        ctrl : true,
	        alt : true,
	        fn: this.xuatKetQua,
	        scope: this
	    }]);
    },
    
    reloadNhanVienByDoiTruong : function(combo, record, index) {
		if (this.nvBanCombo.store.isFiltered()) {
			this.nvBanCombo.store.clearFilter();
		}
		this.nvBanCombo.clearValue();
		var newVal = record.get("id");
		if (newVal != null && newVal != "" && newVal != "NO_DT") {
			this.nvBanCombo.store.filterBy(function(record) {
				return record.get('doiTruong-id') == newVal;
			});
		}
	},
	
	reloadQuanHuyenByThanhPho : function(combo, record, idx) {
		this.quanHuyenCombo.clearValue();
		this.phuongXaCombo.clearValue();
		this.phuongXaCombo.store.removeAll();
		this.quanHuyenCombo.store.setBaseParam('maTinh', record.get('maDuLieu'));
		this.quanHuyenCombo.store.load();
	},
	
	reloadPhuongXaByQuanHuyen : function(combo, record, idx) {
		this.phuongXaCombo.clearValue();
		this.phuongXaCombo.store.setBaseParam('maQuanHuyen', record.get('maDuLieu'));
		this.phuongXaCombo.store.load();
	},
    
    search : function() {
    	var params = this.getForm().getFieldValues();
    	this.disableButtons();
    	this.gridStore.setBaseParam("criteria", Ext.encode(params))
    	this.gridStore.load();
    	this.enableButtons();
    },
    
    xoaDuLieuTimKiem : function() {
    	this.getForm().reset();
    	if (this.gridStore.data.items.length > 0) {
    		this.gridStore.removeAll();
		}
    	var f = this.maHdTextField.getEl();
        f.focus.defer(200, f);
    },
    
    xuatKetQua : function() {
    	this.disableButtons();
    	Utility.processExportWaitingWithParams("timHopDong/export", this.getForm().getFieldValues());
    	this.enableButtons();
    },
    
    hasNoCriteria : function(params) {
    	for (var props in params) {
			if (params[props] != "" && props != 'nvThuNganMoi-id') {
				return false
			}
		}
    	return true
    },
    
    capNhatThuNgan : function() {
    	var idThuNgan = this.doiThuNganCombo.getValue();
    	if (idThuNgan == null || idThuNgan == "") {
    		this.notifyMessage({action : "error", msg : lang.msg.notSelectThuNgan});
    		return
		}
    	
    	var items = this.resultTable.store.data.items;
    	var params = this.getForm().getFieldValues();
    	
    	if (this.hasNoCriteria(params)) {
    		Ext.Msg.alert(lang.text.notice, lang.msg.notAllowAssignAllContracts);
    		return;
    	}
    	
    	var waitingBox = Ext.MessageBox.wait(lang.text.pleaseWait, lang.text.loading);
    	Ext.Ajax.request({
            url : 'timHopDong/changeThuNgan',
            method : 'GET',
            params : {
            	"criteria" : Ext.encode(params),
            	"idThuNgan" : idThuNgan,
            	"isChangeThuNgan" : true
            },
            scope : this,
            success : function(response, opts){
            	waitingBox.hide();
                var result = Ext.decode(response.responseText);
                if (result.success) {
                	var idx = this.doiThuNganCombo.store.findExact("id", idThuNgan);
            		var maThuNgan = this.doiThuNganCombo.store.getAt(idx).get("maNv");
            		for ( var i = 0; i < items.length; i++) {
            			items[i].set("nvThuNgan-maNv", maThuNgan);
					}
                	this.notifyMessage({action : "info", msg : Utility.lookUp(lang.msg.changeThuNganSuccess, result.numOfHd, maThuNgan)});
				} else {
					this.notifyMessage({action : "error", msg : lang.msg.changeThuNganFailed});
				}
            }, 
            failure : function() {
            	waitingBox.hide();
            }
        });
    },
    
    dongHd : function() {
    	var items = this.resultTable.store.data.items;
    	var params = this.getForm().getFieldValues();
    	
    	if (this.hasNoCriteria(params)) {
    		Ext.Msg.alert(lang.text.notice, lang.msg.notAllowCloseAllContracts);
    		return;
    	}
    	Ext.Msg.buttonText.ok = lang.text.ok;
		Ext.Msg.buttonText.cancel = lang.text.cancel;
		Ext.Msg.show({
			title : lang.text.notice,
			msg : lang.msg.confirmDongHd,
			icon: Ext.MessageBox.WARNING,
			buttons: Ext.Msg.OKCANCEL,
			scope : this,
			fn: function(buttonId, text, opts){
				if (buttonId == "ok") {
					var waitingBox = Ext.MessageBox.wait(lang.text.pleaseWait, lang.text.loading);
					Ext.Ajax.request({
						url : 'timHopDong/dongHd',
				        params : {
				        	"criteria" : Ext.encode(params),
			            	"isDongHd" : true
				        },
				        method : 'GET',
				        scope : this,
				        success : function(response, opts){
				        	waitingBox.hide();
				            var result = Ext.decode(response.responseText);
				            if (result.success) {
				            	for ( var i = 0; i < items.length; i++) {
			            			items[i].set("trangThaiText", lang.text.close);
								}
			                	this.notifyMessage({action : "info", msg : Utility.lookUp(lang.msg.dongHdSuccess, result.numOfHd)});
							} else {
								this.notifyMessage({action : "error", msg : lang.msg.dongHdFailed});
							}
				        }, 
				        failure : Ext.emptyFn
					});
				}
			}
		});
    },
    
    giaoPhieuThu : function() {
    	var params = this.getForm().getFieldValues();
    	var waitingBox = Ext.MessageBox.wait(lang.text.pleaseWait, lang.text.loading);
    	Ext.Ajax.request({
			url : 'timHopDong/giaoPhieuThu',
	        params : {
	        	"criteria" : Ext.encode(params),
            	"isDongHd" : true
	        },
	        method : 'GET',
	        scope : this,
	        success : function(response, opts){
	        	waitingBox.hide();
	            var result = Ext.decode(response.responseText);
	            if (result.success) {
                	this.notifyMessage({action : "info", msg : Utility.lookUp(lang.msg.giaoPhieuThuSuccess, result.numOfHd)});
				} else if(result.daGiaoPt){
					this.notifyMessage({action : "error", msg : Utility.lookUp(lang.msg.existHdDaGiaoPhieu, result.numOfHd)});
				} else {
					this.notifyMessage({action : "error", msg : lang.msg.giaoPhieuThuFailed});	
				}
	        }, 
	        failure : function() {
	        	this.notifyMessage({action : "error", msg : lang.msg.giaoPhieuThuFailed});
	        }
		});
    },
    
    defaultActionHandler : function(){
    	this.search();
	}
});